<?php

namespace App\Models;

use Validator;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;

class Cate extends Model
{
    //软删除
    use SoftDeletes;
    protected $dateFormat = 'U';
    protected $datas = ['created_at','updated_at','updated_at'];
    protected $fillable = ['sort','catename'];

    //栏目添加
    public function add ($data)
    {
        $rule = [
            'sort' => 'bail|required|integer',
            'catename' =>'required|unique:cates'
        ];
        $msg = [
            'sort.required' => '排序不能为空',
            'sort.integer' => '排序必须为整数',
            'catename.required' => '栏目不能为空',
            'catename.unique' => '栏目已存在'
        ];

        $volidator = Validator::make($data,$rule,$msg);
        if ($volidator->fails()) {
            return $volidator->errors()->first();
        }

        $result = $this->create($data);
        if ($result) {
            return 1;
        } else {
            return "添加失败";
        }
    }

    //栏目编辑
    public function edit ($data)
    {
        $rule = [
            'sort' => 'bail|required|integer',
            'catename' => 'required|unique:cates'
        ];

        $msg = [
            'sort.required' => "排序不能为空",
            'sort.integer' => "排序必须为整数",
            'catename.required' => "栏目名称不能为空",
            'catename.unique' => "栏目已存在"
        ];

        $volidator = Validator::make ($data,$rule,$msg);
        if ($volidator->fails()){
            return $volidator->errors()->first();
        }

        $cates = $this->find($data['id']);
        $cates->sort = $data['sort'];
        $cates->catename = $data['catename'];
        $result = $cates->save();
        if ($result) {
            return 1;
        } else {
            return "编辑失败";
        }
    }

    //排序
    public function sort($data)
    {
        $rule = [
            'sort' => 'required|integer',
        ];
        $msg = [
            'sort.required' => "排序不能为空",
            'sort.integer' => "排序必须为整数"
        ];

        $volidator = Validator::make($data,$rule,$msg);

        if ($volidator->fails()) {
            return $volidator->errors()->first();
        }

        $cates = $this->find($data['id']);
        $cates->sort = $data['sort'];
        $result = $cates->save();

        if ($result) {
            return 1;
        } else {
            return "排序失败";
        }
    }
}
